package com.xinchao.ck_mips.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.constant.CK;

import com.xinchao.devicemanage.constant.DeviceConstant;
import com.xinchao.devicemanage.util.DeviceDBUtil;
import com.xinchao.devicemanage.util.DeviceTool;
import com.xinchao.devicemanage.util.UpdateTools;
import com.xinchao.machine.digital_advertise.IBaseMachine;
import com.xinchao.machine.digital_advertise.tools.MyToast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import io.reactivex.schedulers.Schedulers;

/**
 * Created by wq on 2019/5/6.
 */
public class DeviceUtil {

    private static MyToast mToast;

    private static DeviceUtil mInstance = null;

    private DeviceUtil() {

    }

    public static DeviceUtil getInstance() {
        if (null == mInstance) {
            synchronized (DeviceUtil.class) {
                if (null == mInstance) {
                    mInstance = new DeviceUtil();
                }
            }
        }

        return mInstance;
    }

    /**
     * 获取终端最近一次开机时间
     * 时间戳
     *
     * @return
     */
    public static long getBootTime() {
        return System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1000000;
    }

    /**
     * 获取终端上一次工作重启后连续工作时间
     * 单位:小时
     *
     * @return
     */
    public static int getWorkingHours() {
        return Math.round((System.currentTimeMillis() - getBootTime()) / 1000 / 60 / 60);
    }

    /**
     * 获取终端上一次工作重启后连续工作时间（分钟）
     * 单位：分钟
     *
     * @return
     */
    public static int getWorkingMinute() {
        return Math.round((System.currentTimeMillis() - getBootTime()) / 1000 / 60);
    }

    /**
     * 获取屏幕分辨率
     *
     * @param mContext
     * @return
     */
    public static String getResolution(Context mContext) {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getRealMetrics(dm);
        return dm.widthPixels + "x" + dm.heightPixels;
    }

    /**
     * 获取终端当前剩余容量
     * 单位:字节
     *
     * @return
     */
    public static long getResidualCapacity() {
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        return freeBlocks * blockSize; //单位byte
    }

    /**
     * 获取设备音量
     *
     * @param mContext
     * @return
     */
    public static int getVolume(Context mContext) {
        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        return Math.round((float) current * 100 / max);
    }

    /**
     * 设置设备音量
     *
     * @param vol
     * @param mContext
     */
    public static void setVolume(int vol, Context mContext) {
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, Math.round((float) vol * max / 100), 0);
    }

    /**
     * 获取内网IP
     *
     * @param mContext
     * @return
     */
    public static String getIP(Context mContext) {
        String ip;
        ConnectivityManager conMann = (ConnectivityManager)
                mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileNetworkInfo.isConnected()) {
            ip = getLocalIpV4Address();
            return ip;
        } else if (wifiNetworkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ip = intToIp(ipAddress);
            return ip;
        }

        return null;
    }

    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
    }

    public static String getLocalIpV4Address() {
        try {
            String ipv4;
            ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
                        ipv4 = address.getHostAddress();
                        return ipv4;
                    }
                }

            }

        } catch (Exception ex) {
            // Log.e("localip", ex.toString());
        }
        return null;
    }

    /**
     * 是否返回横屏
     * changhong :ZLP86Ni 竖屏
     *
     * @return
     */
    public static boolean isLandscape(Context mContext) {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getRealMetrics(dm);
        if (dm.widthPixels > dm.heightPixels) {
            //宽大于高 横屏
            return true;
        } else {
            return false;
        }

    }


    private static void power_off() {
        getInfoBySuCmd("reboot -p");
    }

    /**
     * 命令行执行操作
     *
     * @param cmd
     * @return
     */
    public static String getInfoBySuCmd(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        String out = "";
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int aa = process.waitFor();
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            out = new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        if (TextUtils.isEmpty(out)) {
            return out;
        }
        return out.trim();
    }

    /**
     * 静默安装
     *
     * @param path apk绝对路径
     */
    public static void installApp(String path, Context mContext) {
        switch (getDeviceType()) {
            case DeviceType.DEVICE_HI_DPT_CODE:
                HisiDeviceUtil.installApp(mContext, path);
                break;
            case DeviceType.DEVICE_OTHER_CODE:
                UpdateTools.getInstence(mContext).install(path);
                break;
        }
    }

    /**
     * 设置开关屏幕
     *
     * @param openTime
     * @param closeTime
     * @param context
     */
    public void saveScreenOpenClose(String openTime, String closeTime, Context context) {
        // 保存开关屏时间到本地
        ShareUtil.getInstance().put(CK.OPEN_SCREEN, openTime);
        ShareUtil.getInstance().put(CK.CLOSE_SCREEN, closeTime);
        // 设置开关屏
        startScreen(context);
    }

    public static void startScreen(Context context) {
        Schedulers.io().scheduleDirect(() -> {
            // 取消以前的闹钟
            AlarmManagerUtil.cancelAlarm(context, AlarmManagerUtil.ALARM_ACTION, 0);
            AlarmManagerUtil.cancelAlarm(context, AlarmManagerUtil.ALARM_ACTION, 1);
            // 获取屏幕打开时间
            String openTimeSave = ShareUtil.getInstance().getString(CK.OPEN_SCREEN, "-1");
            if (openTimeSave.equals("-1"))
                return;
            Calendar openTime = DateUtil.stringToCalendar(openTimeSave);
            if (openTime == null)
                return;
            // 设置开屏闹钟
            AlarmManagerUtil.setAlarm(context, 1, openTime.get(Calendar.HOUR_OF_DAY),
                    openTime.get(Calendar.MINUTE), 0, 0, CK.OPEN_SCREEN);
            // 获取屏幕关闭时间
            String closeTimeSave = ShareUtil.getInstance().getString(CK.CLOSE_SCREEN, "-1");
            if (closeTimeSave.equals("-1"))
                return;
            Calendar closeTime = DateUtil.stringToCalendar(closeTimeSave);
            if (closeTime == null)
                return;
            // 设置关屏闹钟
            AlarmManagerUtil.setAlarm(context, 1, closeTime.get(Calendar.HOUR_OF_DAY),
                    closeTime.get(Calendar.MINUTE), 1, 0, CK.CLOSE_SCREEN);
            // 检查当前时间是否在开关屏时间范围内
            checkOnOffTime(context, openTime, closeTime);
        });
    }

    /**
     * 开关屏时间倒计时
     *
     * @param context
     */
    public static void checkOnOffTime(Context context, Calendar begin, Calendar end) {
        if (Build.MODEL.equals(DeviceType.DEVICE_CH3288)) {
            Logger.d("--------->长虹3288不支持开关屏");
            return;
        }
        if (end.before(begin)) {
            Logger.d("--------->关屏时间小于开屏时间");
            return;
        }

        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        // 如果当前时间不在开关屏时间范围内，自动关屏
        if (!DateUtil.belongCalendar(now, begin, end)) {
            offScreenStart(context);
        } else {
            removeOffScreen();
        }

    }

    public static void removeOffScreen() {
        // 取消弹窗
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
    }

    /**
     * 唤醒休眠
     */
    public static void exitSleep(Context mContext) {
        if (Build.MODEL.equals(DeviceType.DEVICE_CH3288)) {// 长虹3288不做处理
            return;
        }
        switch (getDeviceType()) {
            case DeviceType.DEVICE_HI_DPT_CODE:
                HisiDeviceUtil.exitSleep(mContext);
                break;
            case DeviceType.DEVICE_OTHER_CODE:
                //暂时还未支持
                //SmdtManager.create(mContext).smdtSetLcdBackLight(1);
                break;
        }
    }

    public static void offScreenStart(Context context) {
        // 保存声音
        int volCount = DeviceTool.getVol(context);
        ShareUtil.getInstance().put(CK.SP_VOLUME, volCount);
        // 设置静音
        DeviceTool.setVol(0, context);
        // 关屏操作
        goToSleep(context);
    }

    /**
     * 休眠
     */
    public static void goToSleep(Context mContext) {
        if (Build.MODEL.equals(DeviceType.DEVICE_CH3288)) {// 长虹3288不做处理
            return;
        }

        switch (getDeviceType()) {
            case DeviceType.DEVICE_HI_DPT_CODE:
                Intent intent = new Intent("android.intent.action.gotosleep");
                mContext.sendBroadcast(intent);
                break;
            case DeviceType.DEVICE_OTHER_CODE:
                //暂时还未支持
                // SmdtManager.create(context).smdtSetLcdBackLight(0);
                break;
        }
    }

    public static int getDeviceType() {
        if (Build.MODEL.equals(DeviceType.DEVICE_HI_DPT)) {
            return DeviceType.DEVICE_HI_DPT_CODE;
        } else if (Build.MODEL.equals(DeviceType.DEVICE_W4324A88T_A)) {
            return DeviceType.DEVICE_W4324A88T_A_CODE;
        } else {
            return DeviceType.DEVICE_OTHER_CODE;
        }
    }

    /**
     * 设备重启
     *
     * @param mContext
     * @param iBaseMachine
     */
    public void startUp(Context mContext, IBaseMachine iBaseMachine) {
        switch (getDeviceType()) {
            case DeviceType.DEVICE_HI_DPT_CODE:
                HisiDeviceUtil.startUp(mContext);
                break;
            case DeviceType.DEVICE_OTHER_CODE:
                iBaseMachine.reboot();
                break;
        }
    }

    public String deiceCode = "";

    public String getDeviceCode() {
        if (!TextUtils.isEmpty(deiceCode)) {
            return deiceCode;
        }
        try {
            if (!Build.MODEL.equals("HiDPTAndroid") && !TextUtils.isEmpty(DeviceTool.getDeviceCode())) {
                deiceCode = DeviceTool.getDeviceCode();
                return deiceCode;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        deiceCode = DeviceDBUtil.getDBConfigValue(DeviceConstant.COLUMN_MACHINE_CODE);

        return deiceCode;
    }

    /**
     * 关机
     */
    public void shutDown(IBaseMachine iBaseMachine) {
        iBaseMachine.power_off();
    }

    /**
     * 获取设备联网方式
     *
     * @param context
     * @return
     */
    public static String getNetworkState(Context context) {
        String strNetworkType = "WIFI";
        try {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 获取网络服务
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    strNetworkType = "WIFI";
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    strNetworkType = "SIM卡";
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    strNetworkType = "有线";
                } else {
                    strNetworkType = "WIFI";
                }
            }
            return URLEncoder.encode(strNetworkType, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strNetworkType;

    }

    /**
     * 获取屏幕亮度
     * 1：自动调节屏幕亮度
     * 0:手动调节
     *
     * @param context
     * @return
     */
    public static int getScreenMode(Context context) {
        int screenMode = 0;
        try {
            screenMode = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return screenMode;
    }

    /**
     * 获取当前屏幕亮度值
     *
     * @param context
     * @return
     */
    public static int getScreenBrightness(Context context) {
        int screenBrightness = 255;
        try {
            screenBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return screenBrightness;
    }

    /**
     * 设置当前屏幕亮度的模式
     *
     * @param context
     * @param paramInt
     */
    public static void setScreenMode(Context context, int paramInt) {
        try {
            Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 设置当前屏幕亮度
     *
     * @param context
     * @param paramInt
     */
    public static void saveScreenBrightness(Context context, int paramInt) {
        try {
            Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
            android.provider.Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, paramInt);
            context.getContentResolver().notifyChange(uri, null);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 保存当前屏幕亮度值
     *
     * @param context
     * @param param
     */
    public static void setScreenBirghtness(Context context, int param) {
        Window localWindow = ((Activity) context).getWindow();
        WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
        float f = param / 255.0F;
        localLayoutParams.screenBrightness = f;
        localWindow.setAttributes(localLayoutParams);
        //保存
        saveScreenBrightness(context, param);
    }


}
